package com.seleniti.enpareja.web.desktop.client.ui.view;

import org.ioc.commons.impl.gwt.client.model.dataprovider.AsyncPagedDataProvider;
import org.ioc.commons.impl.gwt.client.ui.HasEnabledWrapper;
import org.ioc.commons.impl.gwt.client.ui.HasVisibilityWrapper;
import org.ioc.commons.model.dataprovider.PagedDataProvider;
import org.ioc.commons.ui.HasVisibility;
import org.ioc.commons.ui.features.Info;

import com.google.gwt.cell.client.AbstractSafeHtmlCell;
import com.google.gwt.cell.client.SimpleSafeHtmlCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.DataGrid;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.SimplePager.TextLocation;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.seleniti.enpareja.controller.model.integration.database.domain.CoupleRequest;
import com.seleniti.enpareja.controller.model.integration.database.domain.CoupleRequest.Status;
import com.seleniti.enpareja.controller.ui.view.GetCoupleView;
import com.seleniti.enpareja.controller.ui.view.GetCoupleView.Action;
import com.seleniti.enpareja.controller.ui.view.GetCoupleView.Event;
import com.seleniti.enpareja.controller.ui.view.GetCoupleView.Operation;
import com.seleniti.enpareja.controller.ui.view.GetCoupleView.Presenter;
import com.seleniti.enpareja.controller.ui.view.GetCoupleViewPresenter;
import com.seleniti.enpareja.web.desktop.client.ui.cell.EnParejaTemplate;
import com.seleniti.enpareja.web.desktop.client.ui.resources.CommonResources;
import com.seleniti.enpareja.web.desktop.client.ui.widget.InfoInlineWidget;

public class GetCoupleViewWidget extends EnParejaBaseView<Event, Operation, Action, Presenter> implements GetCoupleView {

	public static EnParejaTemplate template;

	private static TemplateUiBinder uiBinder = GWT.create(TemplateUiBinder.class);

	interface TemplateUiBinder extends UiBinder<Widget, GetCoupleViewWidget> {
	}

	@UiField(provided = true)
	DataGrid<CoupleRequest> lstCoupleRequests;

	@UiField(provided = true)
	SimplePager pager;

	@UiField
	Panel stillPendingActions;
	
	@UiField
	Panel pendingActions;

	@UiField
	Panel rejectedActions;

	@UiField
	Button btnGetCoupleNow;
	
	@UiField
	Button btnReject;
	
	@UiField
	Button btnRequestAgain;
	
	@UiField
	Button btnDismissRequest;	

	@UiField
	Button btnDismissRequest2;	

	@UiField
	CommonResources common;
	
	@UiField
	InfoInlineWidget coupleGotInfo;

	private PagedDataProvider<CoupleRequest> pagedDataProvider;

	private AsyncPagedDataProvider<CoupleRequest, Operation> asyncDataProvider;

	private SingleSelectionModel<CoupleRequest> selectionModel;

	private boolean loading;

	public GetCoupleViewWidget() {
		if (template == null) {
			template = GWT.create(EnParejaTemplate.class);
		}

		this.presenter = new GetCoupleViewPresenter(this, eventbus, operationManager, actionController);

		ProvidesKey<CoupleRequest> keyProvider = new ProvidesKey<CoupleRequest>() {

			@Override
			public Object getKey(CoupleRequest item) {
				return item.getCoupleRequestId();
			}
		};
		this.lstCoupleRequests = new DataGrid<CoupleRequest>(keyProvider);

		this.lstCoupleRequests.addColumn(new Column<CoupleRequest, SafeHtml>(new SimpleSafeHtmlCell()) {

			@Override
			public SafeHtml getValue(CoupleRequest object) {
				return object != null && object.getFrom() != null && object.getFrom().getUserEmail() != null && !object.getFrom().getUserEmail().isEmpty() ? maskEmail(object.
						getFrom().getUserEmail()) : SafeHtmlUtils.fromSafeConstant("-- Sin email --");
			}
		}, "De");

		this.lstCoupleRequests.addColumn(new Column<CoupleRequest, SafeHtml>(new SimpleSafeHtmlCell()) {

			@Override
			public SafeHtml getValue(CoupleRequest object) {
				return object != null && object.getTo() != null && object.getTo().getUserEmail() != null && !object.getTo().getUserEmail().isEmpty() ? maskEmail(object.
						getTo().getUserEmail()) : SafeHtmlUtils.fromSafeConstant("-- Sin email --");
			}
		}, "A");

//		this.lstCoupleRequests.addColumn(new Column<CoupleRequest, String>(new TextCell()) {
//
//			@Override
//			public String getValue(CoupleRequest object) {
//				return object != null && object.getStatus() != null ? object.
//						getStatus().getLabel() : "-- No se sabe --";
//			}
//		}, "Estado");

		AbstractSafeHtmlCell<Status> statusCell = new AbstractSafeHtmlCell<Status>(
				new AbstractSafeHtmlRenderer<Status>() {

					@Override
					public SafeHtml render(Status object) {
						//TODO: Estilizar
						return template.span("", object!=null ? object.getLabel() : "-- No se sabe --");
					}
				}) {

			@Override
			protected void render(com.google.gwt.cell.client.Cell.Context context, SafeHtml data, SafeHtmlBuilder sb) {
				if (data != null) {
					sb.append(data);
				}

			}
		};
		this.lstCoupleRequests.addColumn(new Column<CoupleRequest, Status>(statusCell) {

			@Override
			public Status getValue(CoupleRequest object) {
				return object != null ? object.getStatus() : null;
			}
		}, "Estado");

		this.lstCoupleRequests.setEmptyTableWidget(new HTML("<i>Ninguna petición</i>"));

		this.selectionModel = new SingleSelectionModel<CoupleRequest>(keyProvider);

		this.selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				presenter.onSelectedCoupleRequestChanged();
			}
		});

		this.lstCoupleRequests.setSelectionModel(this.selectionModel);

		this.asyncDataProvider = new AsyncPagedDataProvider<CoupleRequest, Operation>(keyProvider, this, Operation.GettingCoupleRequests,
				this.operationManager, "");
		this.asyncDataProvider.addDataDisplay(lstCoupleRequests);
		pager = new SimplePager(TextLocation.CENTER, false, 0, true);
		pager.setDisplay(lstCoupleRequests);

		initWidget(uiBinder.createAndBindUi(this));
	}

	@Override
	public void startSearch() {
		this.lstCoupleRequests.setVisibleRangeAndClearData(this.lstCoupleRequests.getVisibleRange(), true);
	}

	@Override
	public void setPagedDataProvider(PagedDataProvider<CoupleRequest> dataProvider) {
		this.pagedDataProvider = dataProvider;
		this.lstCoupleRequests.setPageSize(pagedDataProvider.getMinFecthLength());
	}

	@Override
	public PagedDataProvider<CoupleRequest> getPagedDataProvider() {
		return this.pagedDataProvider;
	}

	@UiHandler("btnGetCoupleNow")
	void onGetCoupleNowButtonClicked(ClickEvent evt) {
		this.presenter.onGetCoupleNow();
	}

	@Override
	public CoupleRequest getSelectedCoupleRequest() {
		return this.selectionModel.getSelectedObject();
	}

	@Override
	public HasVisibility pendingActions() {
		return HasVisibilityWrapper.from(pendingActions, this);
	}

	@Override
	public HasVisibility stillPendingActions() {
		return HasVisibilityWrapper.from(stillPendingActions, this);
	}
	
	@UiHandler("btnDismissRequest")
	void onDismissRequestButton(ClickEvent evt) {
		this.presenter.onDismissSelectedRequest();
	}

	@UiHandler("btnDismissRequest2")
	void onDismissRequest2Button(ClickEvent evt) {
		this.presenter.onDismissSelectedRequest();
	}

	@Override
	public HasVisibility rejectedActions() {
		return HasVisibilityWrapper.from(rejectedActions, this);
	}
	
	@UiHandler("btnReject")
	void onRejectButtonClicked(ClickEvent evt) {
		this.presenter.onRejectSelectedRequest();
	}

	@Override
	public void clearSelection() {
		this.selectionModel.clear();
	}

	@Override
	public void setLoading(boolean loading) {
		this.loading=loading;
		HasEnabledWrapper.setEnabled(!loading, btnGetCoupleNow,btnReject,btnDismissRequest,btnDismissRequest2,btnRequestAgain);
	}

	@Override
	public boolean isLoading() {
		return this.loading;
	}
	
	@Override
	public Info coupleGotInfo() {
		return this.coupleGotInfo;
	}
}
